import {
  Form,
  FormInstance,
  Input,
  Modal,
  Notification,
  Select,
} from '@arco-design/web-react';
import locale from './locale';
import useLocale from '@/utils/useLocale';
import { GlobalContext } from '@/context';
import { useContext, useEffect, useRef, useState } from 'react';
import React from 'react';
import FormItem from '@arco-design/web-react/es/Form/form-item';
import { getDictInfo, getDictListByGroupId, updateDict } from '@/api/dict';

function UpdatePage(props: { id: number; visible; setVisible; callback }) {
  const TextArea = Input.TextArea;

  const formRef = useRef<FormInstance>();

  const { lang } = useContext(GlobalContext);

  const [loading, setLoading] = React.useState(false);

  const [dictListSelect, setDictListSelect] = useState([]);

  function fetchSelectsData(dict){
    getDictListByGroupId(dict.group_id).then((res) => {
      const { success, data } = res.data;
      if (success) {
        const selects = [];
        selects.push({
          label: t['searchForm.placeholder'],
          value: '0',
        });
        data[0].map((item) => {
            if (item.id !== dict.id) {
              selects.push({
                label: item.name,
                value: item.id+'',
              });
            }
        })
        setDictListSelect(selects);
      }
    });
  }

  //加载数据
  function fetchData() {
    if (props.id !== undefined && props.visible) {
      setLoading(true);
      getDictInfo(props.id)
        .then((res) => {
          const { success, data } = res.data;
          if (success) {
            data.default = data.default + '';
            data.parent_id = data.parent_id + '';
            fetchSelectsData(data);
            formRef.current.setFieldsValue(data);
          }
          setLoading(false);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }

  useEffect(() => {
    fetchData();
  }, [props.id, props.visible]);

  const t = useLocale(locale);

  //提交修改
  const handleSubmit = () => {
    formRef.current.validate().then((values) => {
      setLoading(true);
      values.default = values.default == 'true';
      values.parent_id = Number(values.parent_id);
      updateDict(values)
        .then((res) => {
          const { success, message } = res.data;
          if (success) {
            Notification.success({ content: message, duration: 1000 });
            props.setVisible(false);
            props.callback();
          }
        })
        .finally(() => {
          setLoading(false);
        });
    });
  };

  return (
    <Modal
      title={t['searchTable.update.title']}
      visible={props.visible}
      onOk={() => {
        handleSubmit();
      }}
      onCancel={() => {
        props.setVisible(false);
      }}
      autoFocus={false}
      focusLock={true}
      confirmLoading={loading}
    >
      <Form
        ref={formRef}
        style={{ width: '95%', marginTop: '6px' }}
        labelCol={{ span: lang === 'en-US' ? 7 : 6 }}
        wrapperCol={{ span: lang === 'en-US' ? 17 : 18 }}
      >
        <FormItem
          required
          label={t['searchTable.columns.id']}
          field={'id'}
          hidden
        >
          <Input />
        </FormItem>
        <FormItem
          label={t['searchTable.columns.parent_id']}
          field={'parent_id'}
          initialValue={'0'}
        >
          <Select
            placeholder={t['searchForm.placeholder']}
            options={dictListSelect}
            allowClear
          />
        </FormItem>
        <FormItem required label={t['searchTable.columns.name']} field={'name'}>
          <Input placeholder={t['searchForm.placeholder']} allowClear />
        </FormItem>
        <FormItem required label={t['searchTable.columns.code']} field={'code'}>
          <Input placeholder={t['searchForm.placeholder']} allowClear />
        </FormItem>
        <FormItem
          required
          label={t['searchTable.columns.value']}
          field={'value'}
        >
          <Input.TextArea
            placeholder={t['searchForm.placeholder']}
            allowClear
          />
        </FormItem>
        <FormItem
          required
          label={t['searchTable.columns.default']}
          field={'default'}
          initialValue={'false'}
        >
          <Select
            placeholder={t['searchForm.placeholder']}
            options={[
              {
                label: t['searchTable.columns.yes'],
                value: 'true',
              },
              {
                label: t['searchTable.columns.no'],
                value: 'false',
              },
            ]}
            allowClear
          />
        </FormItem>
        <FormItem
          required
          label={t['searchTable.columns.dict_desc']}
          field={'dict_desc'}
        >
          <Input.TextArea
            placeholder={t['searchForm.placeholder']}
            allowClear
          />
        </FormItem>
      </Form>
    </Modal>
  );
}

export default UpdatePage;
